# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2005-2006 CamptoCamp
# Copyright (c) 2006-2010 OpenERP S.A
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import time, os
from openerp.osv import osv, fields
from openerp.tools.translate import _
from openerp.report import report_sxw
import locale
locale.setlocale(locale.LC_ALL, '')

class gatepass_report(report_sxw.rml_parse):
    _name = 'gatepass.report'

    def _search_data(self, cr, uid, ids, data_obj, val_data, filter_selection, default_from, default_to, input_from, input_to, selection_ids, context=None):
        data_header = ''
        data_ids = []

        if context is None:
            context = {}
        
        if filter_selection == 'all_vall':
            data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'def':
            data_found = False
            if default_from and data_obj.browse(cr, uid, default_from) and data_obj.browse(cr, uid, default_from).name:
                default_from_header = data_obj.browse(cr, uid, default_from).name
                data_found = True
                val_data.append(('name', '>=', default_from_header))
            if default_to and data_obj.browse(cr, uid, default_to) and data_obj.browse(cr, uid, default_to).name:
                default_to_header = data_obj.browse(cr, uid, default_to).name
                data_found = True
                val_data.append(('name', '<=', default_to_header))
            if data_found:
                data_header = '"' + default_from_header + '" - "' + default_to_header + '"'
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'input':
            data_found = False
            if input_from:
                data_ids_from = data_obj.search(cr, uid, [('name','=ilike', input_from + '%')], order="name", limit=1)
                if data_ids_from:
                    input_from_name = data_obj.browse(cr, uid, data_ids_from[0]).name
                    data_found = True
                    val_data.append(('name', '>=', input_from_name))
            if input_to:
                data_ids_to = data_obj.search(cr, uid, [('name','=ilike', input_to + '%')], order="name desc", limit=1)
                if data_ids_to:
                    input_to_name = data_obj.browse(cr, uid, data_ids_to[0]).name
                    data_found = True
                    val_data.append(('name', '<=', input_to_name))
            data_header = '"' + input_from + '" - "' + input_to + '"'
            if data_found:
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'selection':
            if selection_ids:
                sel_ids = ''
                for sel in  data_obj.browse(cr, uid, selection_ids):
                    sel_ids += ('"%s",')%(sel.name,)

                data_header = '[' + sel_ids +']'
                data_ids = selection_ids
                
        return data_header, data_ids
    
    def set_context(self, objects, data, ids, context=None):
        new_ids = ids
        
        if context is None:
            context = {}
            
        self.sortby_ids = data['form']['sortby_ids'] or False
        date_from = data['form']['date_from']
        date_to = data['form']['date_to']
        
        output_date_header = ''
        val_date = []
        if data['form']['date_filter_selection'] == 'date_sel':
            if date_from and not date_to:
                output_date_header = 'Date Start From : %s' % (date_from,)
                val_date.append(('date','>=',str(date_from)))
            elif date_to and not date_from:
                output_date_header = 'Date Until : %s' % (date_to,)
                val_date.append(('date','<=',str(date_to))) 
            elif date_to and date_from:
                output_date_header = 'Date Start From : %s, Until: %s' % (date_from, date_to)
                val_date.append(('date','>=',str(date_from)))
                val_date.append(('date','<=',str(date_to)))

        self.output_date_header = output_date_header
        self.val_date = val_date
        
        self.output_im_header, self.im_ids = self._search_data(self.cr, self.uid, ids, self.pool.get('stock.picking'),
                                                                                      [('picking_type_id.code','=','internal'),('state','!=','cancel'),('gate_pass','=',True)],
                                                                                      data['form']['im_filter_selection'],
                                                                                      data['form']['im_def_from'] and data['form']['im_def_from'][0] or False,
                                                                                      data['form']['im_def_to'] and data['form']['im_def_to'][0] or False,
                                                                                      data['form']['im_input_from'] or False,
                                                                                      data['form']['im_input_to'] or False,
                                                                                      data['form']['im_no_ids'] or False,
                                                                                      context=context)
        
        self.output_requestor_header, self.requestor_ids = self._search_data(self.cr, self.uid, ids, self.pool.get('res.users'),
                                                                                      [],
                                                                                      data['form']['requestor_filter_selection'],
                                                                                      data['form']['requestor_def_from'] and data['form']['requestor_def_from'][0] or False,
                                                                                      data['form']['requestor_def_to'] and data['form']['requestor_def_to'][0] or False,
                                                                                      data['form']['requestor_input_from'] or False,
                                                                                      data['form']['requestor_input_to'] or False,
                                                                                      data['form']['requestor_name_ids'] or False,
                                                                                      context=context)
        
        
        self.output_project_header, self.project_ids = self._search_data(self.cr, self.uid, ids, self.pool.get('project.project'),
                                                                                      [('state', '!=', 'cancelled')],
                                                                                      data['form']['project_filter_selection'],
                                                                                      data['form']['project_def_from'] and data['form']['project_def_from'][0] or False,
                                                                                      data['form']['project_def_to'] and data['form']['project_def_to'][0] or False,
                                                                                      data['form']['project_input_from'] or False,
                                                                                      data['form']['project_input_to'] or False,
                                                                                      data['form']['project_name_ids'] or False,
                                                                                      context=context)

        self.output_cust_header, self.cust_ids = self._search_data(self.cr, self.uid, ids, self.pool.get('res.partner'),
                                                                                      [],
                                                                                      data['form']['cust_filter_selection'],
                                                                                      data['form']['cust_def_from'] and data['form']['cust_def_from'][0] or False,
                                                                                      data['form']['cust_def_to'] and data['form']['cust_def_to'][0] or False,
                                                                                      data['form']['cust_input_from'] or False,
                                                                                      data['form']['cust_input_to'] or False,
                                                                                      data['form']['cust_name_ids'] or False,
                                                                                      context=context)
        
        return super(gatepass_report, self).set_context(objects, data, new_ids)

    def __init__(self, cr, uid, name, context=None):
        super(gatepass_report, self).__init__(cr, uid, name, context=context)
        self.localcontext.update({
            'time': time,
            'locale': locale,
            'get_printed_date' : self._get_printed_date,
            'get_printed_by': self._get_printed_by,
            'get_decimal_accuracy_uom': self._get_decimal_accuracy_uom,
            'get_output_date_header': self._get_output_date_header,
            'get_output_im_header': self._get_output_im_header,
            'get_output_requestor_header': self._get_output_requestor_header,
            'get_output_project_header': self._get_output_project_header,
            'get_output_cust_header': self._get_output_cust_header,
            'get_output_sortby_header': self._get_output_sortby_header,
            'get_lines': self._get_lines,
            })
    
    def _get_printed_date(self):
        header = ''
        user_obj = self.pool.get('res.users')
        user_ids = user_obj.search(self.cr, self.uid, [('id','=',self.uid)])
        if user_ids :
            tz = user_obj.browse(self.cr, self.uid, user_ids[0])
            tz_name = tz.tz
        os.environ['TZ'] = tz_name
        time.tzset()
        header = 'Printed date : ' + time.strftime("%Y/%m/%d") + '  Time : '+ time.strftime("%H:%M:%S")
         
        return header
    
    def _get_printed_by(self):
        header =''
        user_obj = self.pool.get('res.users')
        user_ids = user_obj.search(self.cr, self.uid, [('id','=',self.uid)])
        if user_ids :
            user_id = user_obj.browse(self.cr, self.uid, user_ids[0])
            user_name = user_id.name
        
        header = 'Printed by : ' + user_name
        
        return header
    
    def _get_decimal_accuracy_uom(self):
        dp = 3
        dp_obj = self.pool.get('decimal.precision')
        dp_ids = dp_obj.search(self.cr, self.uid, [('name','=','Product Unit of Measure')])
        if dp_ids :
            dp_id = dp_obj.browse(self.cr, self.uid, dp_ids[0])
            dp = dp_id.digits
        return dp   
    
    def _get_output_date_header(self):
        header = ''
        if self.output_date_header:
            header = self.output_date_header
         
        return header
    
    def _get_output_im_header(self):
        header = ''
        if self.output_im_header:
            header = 'GP No. : ' + self.output_im_header
         
        return header
    
    def _get_output_requestor_header(self):
        header = ''
        if self.output_requestor_header:
            header = 'Requestor : ' + self.output_requestor_header
         
        return header
    
    def _get_output_project_header(self):
        header = ''
        if self.output_project_header:
            header = 'Project : ' + self.output_project_header
         
        return header
    
    def _get_output_cust_header(self):
        header = ''
        if self.output_emp_header:
            header = 'Customer : ' + self.output_cust_header
         
        return header
    
    def _get_output_sortby_header(self):
        header = output_sortby_header = ''
        result = []
        
        if self.sortby_ids:
            transfer_sortby_ids = self.pool.get('param.gatepass.report.sortby').search(self.cr, self.uid, [('id', 'in', self.sortby_ids)], order='seq desc')
        
        if transfer_sortby_ids:
            for item in self.pool.get('param.gatepass.report.sortby').browse(self.cr, self.uid, transfer_sortby_ids):
                result.append({
                        'seq' : item['seq'],
                        'sort_by' : item['sort_by'],
                        })
            result = result and sorted(result, key=lambda val_res: val_res['seq']) or []               
            
            for rs in result:
                sort_name = ''
                if rs['sort_by'] == 'date':
                    sort_name = 'Date'
                elif rs['sort_by'] == 'im_no':
                    sort_name = 'GP No'
                elif rs['sort_by'] == 'requestor_name':
                    sort_name = 'Requestor'
                elif rs['sort_by'] == 'project_name':
                    sort_name = 'Project'
                elif rs['sort_by'] == 'cust_name':
                    sort_name = 'Customer'
                output_sortby_header += ('"%s",')%(sort_name,)
            header = 'Sort By : ' + output_sortby_header

        return header
    
    def _get_lines(self):
        cr  = self.cr
        uid = self.uid
        
        user_obj            = self.pool.get('res.users')
        stock_move_obj      = self.pool.get('stock.move')
        stock_picking_obj   = self.pool.get('stock.picking')
        transfer_sortby_obj = self.pool.get('param.gatepass.report.sortby')

        results      = []
        val_transfer = [('picking_type_id.code','=','internal'),('state','!=','cancel'),('gate_pass','=',True),('project_id2.state','!=','cancelled')]
        
        output_sortby_header = ''
        
        if self.val_date:
            val_transfer += self.val_date
        if self.im_ids:
            val_transfer.append(('id','in',self.im_ids))
        if self.requestor_ids:
            val_transfer.append(('requestor_id','in',self.requestor_ids))
        if self.project_ids:
            val_transfer.append(('project_id2','in',self.project_ids))
        if self.cust_ids:
            val_transfer.append(('project_id2.analytic_account_id.partner_id','in',self.cust_ids))
        
        transfer_sortby_ids = []
        if self.sortby_ids:
            transfer_sortby_ids = transfer_sortby_obj.search(cr, uid, [('id', 'in', self.sortby_ids)], order='seq desc')
            
        transfer_ids = stock_picking_obj.search(cr, uid, val_transfer)
        if transfer_ids:
            transfer_im_ids = []
            
            for im in stock_picking_obj.browse(cr, uid, transfer_ids):
                
                move_lines = []
                move_lines_ids = stock_move_obj.search(cr, uid,[('picking_id','=',im.id)])
                for sml in stock_move_obj.browse(cr, uid, move_lines_ids, context=None) :
                    move_lines.append({  
                        'description' : sml.name,
                        'product_qty' : sml.product_uom_qty,
                        'product_uom': sml.product_uom.name,
                       })
                
                transfer_im_ids.append({
                    'date' : im.date[:10],
                    'im_no' : im.name,
                    'requestor_name' : im.requestor_id.name,
                    'project_name' : im.project_id2.name,
                    'cust_name' : im.project_id2.analytic_account_id.partner_id.name,
                    'remark': im.remark,
                    'move_lines': move_lines,
                })

            if transfer_sortby_ids:
                for transfer_sortby in transfer_sortby_obj.browse(cr, uid, transfer_sortby_ids):
                    transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res[transfer_sortby.sort_by]) or []               
            else:
                transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res['cust_name']) or []
                transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res['project_name']) or []
                transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res['requestor_name']) or []
                transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res['im_no']) or []
                transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res['date']) or []
            
            for transfer_result in transfer_im_ids:
                results.append({
                    'date' : transfer_result['date'] or '',
                    'im_no' : transfer_result['im_no'] or '',
                    'requestor_name' : transfer_result['requestor_name'] or '',
                    'project_name' : transfer_result['project_name'] or '',
                    'cust_name' : transfer_result['cust_name'] or '',
                    'remark' : transfer_result['remark'] or '',          
                    'move_lines' : transfer_result['move_lines'] or '',
                })
     
        return results
        
report_sxw.report_sxw('report.gatepass.report_landscape', 'param.gatepass.report',
    'addons/batam_fast_module/stock/report/report/gatepass_report.rml', parser=gatepass_report, header=False)
